package io.coderyeah.ymcc.exception;

import io.coderyeah.ymcc.enums.YmccSystemError;
import io.coderyeah.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author lqs
 * @date 2022/10/19 11:06
 */
@RestControllerAdvice // controller全局异常处理
@Slf4j
public class GlobalExceptionHandler {

    // 定义需要捕获的业务异常 主动抛出的异常
    @ExceptionHandler(BusinessException.class)
    public JSONResult businessException(HttpServletResponse response, BusinessException ex) {
//        log.warn("业务异常：{}", ex.getSystemError().getMessage() + ":" + ex.getSystemError().getCode());
        log.warn("错误代码：{}", response.getStatus());
        return JSONResult.error(ex.getSystemError());
    }

    // 定义需要捕获的系统异常 未知情况下发生的异常
    @ExceptionHandler(Exception.class)
    public JSONResult globalException(HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        log.warn("全局系统异常：{}", ex.getMessage());
        log.warn("错误代码：{}", response.getStatus());
        return JSONResult.error(YmccSystemError.SYSTEM_ERROR);
    }

    // 定义需要捕获的系统异常 未知情况下发生的异常
    @ExceptionHandler(RuntimeException.class)
    public JSONResult runtimeException(HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        log.warn("全局系统异常：{}", ex.getMessage());
        log.warn("错误代码：{}", response.getStatus());
        return JSONResult.error(ex.getMessage());
    }

    // 定义需要捕获的参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult parameterException(HttpServletResponse response, MethodArgumentNotValidException ex) {
//        ex.printStackTrace();
        final StringBuffer paramInfo = new StringBuffer("数据格式错误：");
        final List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        errors.forEach(err -> {
            paramInfo.append(err.getDefaultMessage()).append(";");
        });
        // 去除末尾分号
        paramInfo.deleteCharAt(paramInfo.lastIndexOf(";"));
        log.warn("参数异常：{}", paramInfo.toString());
        log.warn("错误代码：{}", response.getStatus());
        return JSONResult.error(paramInfo.toString(), YmccSystemError.SYSTEM_PARAM_ERROR.getCode());
    }

}
